import { saveAccount } from '@/services/api/api-admin-account';
import { getWxmpAccountPage } from '@/services/api/api-admin-wxmp-account';
import { PlusOutlined } from '@ant-design/icons';
import { ActionType, ProList } from '@ant-design/pro-components';
import ProForm, {
  DrawerForm,
  ProFormInstance,
  ProFormSelect,
  ProFormText,
} from '@ant-design/pro-form';
import ProTable from '@ant-design/pro-table';
import { Button, Checkbox, Descriptions, message, Space, Tag } from 'antd';
import React, { useRef, useState } from 'react';
import AddAccountOrganization from './AddAccountOrganization';

interface AddAccountProps {
  onRefurbish: () => void;
}
const AddAccount: React.FC<AddAccountProps> = ({ onRefurbish }) => {
  const formRef = useRef<ProFormInstance>();
  const userRef = useRef<ActionType>();

  const [saveAccountOrganizations, setSaveAccountOrganizationsState] = useState<
    AdminAccountBo.AccountOrganizationSaveBo[]
  >([]);
  // 定义一个状态来跟踪所选项
  const [selectedItemId, setSelectedItemId] = useState();

  const [selectedWxmpAccountRowKeys, setSelectedWxmpAccountKeysState] = useState<React.Key[]>([]);
  const onselectlOginId = (e: any) => {
    const checked = e.target.checked;
    const index1 = e.target.value;
    setSaveAccountOrganizationsState(
      saveAccountOrganizations.map((item, index) => {
        item.isDefaultLogin = checked && index === index1;
        return item;
      }),
    );
  };
  return (
    <DrawerForm
      key="add_account_drawer"
      title="新增用户"
      drawerProps={{
        destroyOnClose: true,
      }}
      trigger={
        <Button type="primary">
          <PlusOutlined />
          新建
        </Button>
      }
      formRef={formRef}
      onOpenChange={(open) => {
        if (open) {
        } else {
          setSaveAccountOrganizationsState([]);
        }
      }}
      onFinish={async (values) => {
        if (values.pinCode !== undefined && values.pinCode.length !== 1) {
          values.pinCode = values.pinCode[0];
        } else {
          values.pinCode = undefined;
        }

        if (saveAccountOrganizations.length === 0) {
          message.warning('请添加关联单位');
          return false;
        }

        const value = saveAccountOrganizations.map((item) => {
          const organization = item.organizations[item.organizations.length - 1];
          return {
            organizationId: organization.organizationId,
            organizationCascaderIds: item.organizations.map((item) => item.organizationId),
            organizationCascaderNames: item.organizations.map((item) => item.organizationName),
            roleIds: item.roles.map((item) => item.roleId),
            seq: item.seq,
            marks: item.marks,
            isDefaultLogin: item.isDefaultLogin,
            state: 1,
          };
        });

        const response = await saveAccount({
          organizations: value,
          ...values,
        });
        if (response.code === 0) {
          message.success('提交成功');
          onRefurbish();
          return true;
        } else {
          return false;
        }
      }}
    >
      <ProForm.Group>
        <ProFormText
          width="md"
          name="name"
          label="账号"
          rules={[{ required: true, message: '请输入账号' }]}
        />
        <ProFormText
          width="md"
          name="phone"
          label="电话"
          extra="1703号段是给渝快政未提供手机号的用户注册使用，结构：1703+补位（0）+uuid"
          rules={[{ required: true, message: '请输入电话' }]}
        />
      </ProForm.Group>
      <ProForm.Group>
        <ProFormSelect
          name="pinCode"
          label="关联微信公众号用户身份识别码"
          showSearch
          fieldProps={{
            mode: 'multiple',
            allowClear: true,
            showSearch: true,
            showArrow: false,
            open: false,
            optionFilterProp: 'children',
            filterOption: (input: any, option: any) => {
              console.log(option);
              // return option.options.filter((item: any) => item.label.includes(input));
              return option.label.includes(input);
            },
            listHeight: 500,
            style: {
              width: 488,
            },
          }}
          addonAfter={
            <DrawerForm
              title="关联微信公众号用户列表"
              trigger={<a key="activeSaveAssign">点击添加</a>}
              autoFocusFirstInput
              drawerProps={{
                destroyOnClose: true,
              }}
              onOpenChange={(visible: boolean) => {
                if (visible) {
                  const pinCode = formRef.current?.getFieldValue('pinCode') as [];
                  if (pinCode) {
                    setSelectedWxmpAccountKeysState([...pinCode]);
                  }
                }
              }}
              submitter={false}
            >
              <ProTable<AdminAccountData.WxmpAccount>
                ghost
                rowSelection={{
                  selectedRowKeys: selectedWxmpAccountRowKeys,
                  type: 'radio',
                  onChange: (selectedRowKeys: React.Key[], selectedRows: any) => {
                    setSelectedWxmpAccountKeysState(selectedRowKeys);
                    formRef.current?.setFieldsValue({
                      pinCode: selectedRowKeys,
                    });
                  },
                }}
                tableAlertRender={false}
                columns={[
                  {
                    title: '身份识别码',
                    key: 'pinCode',
                    dataIndex: 'pinCode',
                  },
                  {
                    title: '关注时间',
                    key: 'createdTime',
                    dataIndex: 'createdTime',
                    hideInSearch: true,
                    width: 200,
                  },
                ]}
                request={async (params = {}) => {
                  const response = await getWxmpAccountPage({
                    ...params,
                  });
                  return Promise.resolve({
                    data: response.data.data,
                    total: response.data.total,
                    success: response.code === 0,
                  });
                }}
                rowKey="id"
                tableLayout="fixed"
                dateFormatter="string"
                headerTitle={false}
                bordered
                options={{
                  search: {
                    name: 'pinCode',
                    onSearch: (keyword: string) => {
                      setSelectedWxmpAccountKeysState([]);
                      formRef.current?.setFieldsValue({
                        pinCode: undefined,
                      });
                      return true;
                    },
                  },
                }}
                search={false}
                pagination={{
                  showQuickJumper: true,
                  showSizeChanger: true,
                  defaultPageSize: 50,
                }}
              />
            </DrawerForm>
          }
        />
      </ProForm.Group>
      <ProList<AdminAccountBo.AccountOrganizationSaveBo>
        ghost
        rowKey="id"
        headerTitle="关联单位"
        actionRef={userRef}
        toolBarRender={() => [
          <AddAccountOrganization
            key="add_account_organization"
            onRefurbish={(value: AdminAccountBo.AccountOrganizationSaveBo) => {
              console.log('==========', saveAccountOrganizations, value);

              const isContained = saveAccountOrganizations.some(
                (item) =>
                  item.organizationCascaderIds.toString() ===
                  value.organizationCascaderIds.toString(),
              );

              if (isContained) {
                message.warning('请勿添加重复单位！');
                return false;
              }

              saveAccountOrganizations.push(value);
              console.log(saveAccountOrganizations);

              if (saveAccountOrganizations.length === 1) {
                saveAccountOrganizations[0].isDefaultLogin = true;
              }
              setSaveAccountOrganizationsState(saveAccountOrganizations);
              userRef.current?.reset();
              return true;
            }}
          />,
        ]}
        dataSource={saveAccountOrganizations}
        showActions="hover"
        editable={{
          onSave: async (key, record, originRow) => {
            console.log(key, record, originRow);
            return true;
          },
        }}
        metas={{
          title: {
            render: (text, row, index) => {
              return (
                <div>
                  <Descriptions>
                    <Descriptions.Item label="单位">
                      <Space size={0}>
                        {row.organizations.map((item) => {
                          return (
                            <Tag color="blue" key={item.organizationId}>
                              {item.organizationName}
                            </Tag>
                          );
                        })}
                      </Space>
                      <Checkbox
                        value={index}
                        onChange={onselectlOginId}
                        checked={row.isDefaultLogin}
                      >
                        设为默认登陆
                      </Checkbox>
                    </Descriptions.Item>
                  </Descriptions>
                  {row?.marks && row?.marks.length > 0 && (
                    <Descriptions>
                      <Descriptions.Item label="标记">
                        <Space size={0}>
                          {row?.marks?.map((item) => (
                            <Tag key={item} color="orange">
                              {item}
                            </Tag>
                          ))}
                        </Space>
                      </Descriptions.Item>
                    </Descriptions>
                  )}
                </div>
              );
            },
          },
          description: {
            render: (text, row) => {
              return (
                <Space direction="vertical" size={0} style={{ display: 'flex' }}>
                  <Descriptions>
                    <Descriptions.Item label="角色">
                      <Space size={6} wrap>
                        {row.roles.map((item) => (
                          <Tag key={item.roleId}>{item.roleName}</Tag>
                        ))}
                      </Space>
                    </Descriptions.Item>
                  </Descriptions>
                  {/* </ProCard> */}
                </Space>
              );
            },
          },
          actions: {
            render: (text, row, index, action) => [
              <a
                key="link"
                onClick={(e) => {
                  setSaveAccountOrganizationsState(
                    saveAccountOrganizations.filter(
                      (item) =>
                        item.organizationCascaderIds.toString() !==
                        row.organizationCascaderIds.toString(),
                    ),
                  );
                }}
              >
                删除
              </a>,
            ],
          },
        }}
      />
    </DrawerForm>
  );
};
export default AddAccount;
